import logging
import sched
import signal
import logging.config
from time import sleep, time
from os import path, abort
from yaml import safe_load
from json import dumps, loads
from .mqtt_client import Mqttclient
from .program_sig import Program_sys
from .clearLogManage import ClearLogManage


class Statushost:
    def __init__(self, config_file: str = None) -> None:
        signal.signal(signal.SIGINT, lambda _, __: self.stop())
        if config_file is None:
            config_file = path.dirname(path.dirname(path.abspath(__file__))) + \
                          '/config/main_conf.yaml'.replace('/', path.sep)

        self.config_path = path.dirname(path.abspath(config_file)) + path.sep
        with open(config_file, encoding='utf-8') as general_config:
            self._config = safe_load(general_config)
        logging.config.fileConfig(
            self.config_path + "logs.conf", disable_existing_loggers=False
        )
        self._stopped = True
        global _log
        _log = logging.getLogger('service')
        self._uptopic = self._config.get("upTopic", "虚拟设备/状态监控/网关监控")
        self._getMessageInterval = self._config.get("getMessageInterval", 60)
        self._sched = sched.scheduler(time, sleep)
        self._mqttclient = Mqttclient(self._config)

    # 轮询
    def _upsendtask(self, currtime: float):
        interval = self._getMessageInterval
        nexttime = currtime + interval
        cpu = Program_sys.getCPU()
        disk = Program_sys.getDISK()
        self._mqttclient.send_Msg(self._uptopic, {"cpu": f"{cpu}%", "disk": f"{disk}%"})
        if disk > self._config.get('maxDisk', '80'):
            ClearLogManage.clearLog(self._config)

        self._sched.enterabs(nexttime, 1, lambda: self._upsendtask(nexttime))

    def start(self):
        _log.info("service start!")
        curtime = time()
        self._mqttclient.start()

        self._upsendtask(curtime)
        self._stopped = False
        while not self._stopped:
            next_time = self._sched.run(False)
            if next_time > 0.1:
                sleep(next_time - 0.01)

    def stop(self):
        self._mqttclient.stop()
        self._stopped = True
        _log.info("service stop!")
        abort()
